package cn.cmcc.online.smsapi.sdk.db.entity;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;

public class XmlResdownloadManager {

    public static final int NOTFINISH = 0;
    public static final int FINISH = 1;
    public static final String ID = "id";
    public static final String SCENE_ID = "scene_id";
    public static final String URL = "url";
    public static final String STATUS = "status";// 0未下载(包括还没下载完的)，1下载完毕
    public static final String POS = "pos";
    public static final String INSERT_TIME = "insert_time";// 入库时间
    public static final String LASTLOADTIME = "last_load_time";
    public static final String TABLE_NAME = "tb_xml_res_download";
    public static final String SCENETYPE = "sceneType";// 0:弹窗 1:汽泡

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + " (" + ID
            + " INTEGER PRIMARY KEY," + SCENE_ID + " TEXT," + URL + " TEXT," + STATUS + " INTEGER," + POS + " INTEGER,"
            + LASTLOADTIME + " INTEGER DEFAULT '0' ," + SCENETYPE + " INTEGER DEFAULT '0'," + INSERT_TIME
            + " INTEGER DEFAULT '0' " + ")";

    public static ContentValues setValues(String scene_id, String url, int status, int pos, int sceneType) {
        ContentValues values = new ContentValues();
        values.put(SCENE_ID, scene_id);
        values.put(URL, url);
        values.put(STATUS, status);
        values.put(POS, pos);
        values.put(SCENETYPE, sceneType);
        values.put(INSERT_TIME, System.currentTimeMillis());
        return values;
    }

    public static boolean isXmlResDownloaded(String url) {
        if (StringUtils.isNull(url))
            return false;
        XyCursor cur = null;
        try {
            cur = DBManager.query(TABLE_NAME, new String[] { ID, URL, STATUS }, URL + " = ? and " + STATUS + " = ?",
                    new String[] { url + "", FINISH + "" });
            if (cur != null && cur.getCount() > 0) {
                return true;
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "isXmlResDownloaded: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return false;

    }

    public static void insertOrUpdate(String scene_id, String url, int status, int pos, int scenceType) {

        XyCursor xyCursor = null;
        try {
            xyCursor = DBManager.query(TABLE_NAME, new String[] { ID, SCENE_ID, URL, STATUS, POS }, URL + " = ? ",
                    new String[] { url });
            if (xyCursor != null && xyCursor.getCount() > 0) {

            } else {
                ContentValues values = setValues(scene_id, url, status, pos, scenceType);
                DBManager.insert(TABLE_NAME, values);

            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "insertOrUpdate: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }

    }

    public static void updateXmlResdownloadStatus(long id, int status) {
        try {
            ContentValues values = new ContentValues();
            values.put(STATUS, status);
            DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] { id + "" });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "updateXmlResdownloadStatus: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {

        }
    }

    public static void deleteAll() {
        try {
            DBManager.delete(TABLE_NAME, null, null);

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "deleteAll: " + e.getMessage(), e);
            /* SDK-550 hewengao 20160719 end */
        }
    }

    private static void updateLoadTime(XmlResdownload resdownload) {

        try {

            ContentValues values = new ContentValues();
            values.put(LASTLOADTIME, System.currentTimeMillis() + "");
            DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] { resdownload.id + "" });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "updateLoadTime error: ", e);
            /* SDK-550 hewengao 20160719 end */
		}finally{
			
		}
	
	}
	
	public  static void updateLoadTime(XmlResdownload resdownload,long time){

		try {
			
			ContentValues values = new ContentValues();
			values.put(LASTLOADTIME, time+"");
			DBManager.update(TABLE_NAME, values, ID+" = ? ", new String[]{resdownload.id+""});
		
		
		} catch (Throwable e) {
//			e.printStackTrace();
            LogManager.w(Constant.TAG, "updateLoadTime error: ", e);
		}finally{
			
		}
	
	}

	public static XmlResdownload getOneNotFinishDownload(){		
		XyCursor xyCursor=null;
		try {
			
			xyCursor=DBManager.query(TABLE_NAME, new String[]{ID,SCENE_ID,URL,STATUS,POS,SCENETYPE}, STATUS+"= ? and last_load_time < ?",
					new String[]{NOTFINISH+"",System.currentTimeMillis()-3600*6*1000+""},null, null,"id asc","1");
			if(xyCursor!=null&&xyCursor.getCount()>0 ){
				int idIndex=xyCursor.getColumnIndex(ID);
				int scenceIndex=xyCursor.getColumnIndex(SCENE_ID);						
				int statusIndex=xyCursor.getColumnIndex(STATUS);
				int posIndex=xyCursor.getColumnIndex(POS);
				int urlIndex=xyCursor.getColumnIndex(URL);
				int sceneTypeIndex= xyCursor.getColumnIndex(SCENETYPE);
				while(xyCursor.moveToNext())
				{
					long id =xyCursor.getLong(idIndex);
					String scenceId = xyCursor.getString(scenceIndex);
					int  status = xyCursor.getInt(statusIndex);
					int pos = xyCursor.getInt(posIndex);
					int sceneType = xyCursor.getInt(sceneTypeIndex);
					String url = xyCursor.getString(urlIndex);
					XmlResdownload resdownload = new XmlResdownload();
					resdownload.id =id;
					resdownload.scene_id =scenceId;
					resdownload.status=status;
					resdownload.pos=pos;
					resdownload.url=url;
					resdownload.sceneType=sceneType;
					updateLoadTime(resdownload);
					return resdownload;
					
				}			
			}
		
		} catch (Throwable e) {
			// TODO: handle Throwable
		}finally{
		    XyCursor.closeCursor(xyCursor, true);
		}
		return null;
		
	}
	//获取1个还没下载完的XmlResdownload
	public static XmlResdownload getNeedPriorDownUrlData(String url){		
		XyCursor xyCursor=null;
		try {
			
			xyCursor=DBManager.query(TABLE_NAME, new String[]{ID,SCENE_ID,URL,STATUS,POS,SCENETYPE}, STATUS+"= ? and url =? ",
					new String[]{NOTFINISH+"",url},null, null,"id asc","1");
			if(xyCursor!=null&&xyCursor.getCount()>0 ){
				int idIndex=xyCursor.getColumnIndex(ID);
				int scenceIndex=xyCursor.getColumnIndex(SCENE_ID);						
				int statusIndex=xyCursor.getColumnIndex(STATUS);
				int posIndex=xyCursor.getColumnIndex(POS);
				int urlIndex=xyCursor.getColumnIndex(URL);
				int sceneTypeIndex= xyCursor.getColumnIndex(SCENETYPE);
				while(xyCursor.moveToNext())
				{
					long id =xyCursor.getLong(idIndex);
					String scenceId = xyCursor.getString(scenceIndex);
					int  status = xyCursor.getInt(statusIndex);
					int pos = xyCursor.getInt(posIndex);
					int sceneType = xyCursor.getInt(sceneTypeIndex);
				    url = xyCursor.getString(urlIndex);
				    XmlResdownload resdownload = new XmlResdownload();
					resdownload.id =id;
					resdownload.scene_id =scenceId;
					resdownload.status=status;
					resdownload.pos=pos;
					resdownload.url=url;
					resdownload.sceneType=sceneType;
					updateLoadTime(resdownload);
					return resdownload;
					
				}			
			}
		
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "getNeedPriorDownUrlData error：", e);
            /*SDK-550 hewengao 20160719 end*/
		}finally{
		    XyCursor.closeCursor(xyCursor, true);
		}
		return null;
		
	}
	
}
